package top.aylan.org.filter;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import top.aylan.org.tools.Locale;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LocaleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        String lang = Locale.CN_ZH.getLang();
        Cookie [] cookies = ((HttpServletRequest)servletRequest).getCookies();
        if(cookies!=null){
            for (Cookie cookie :cookies){
                if("lang".equals(cookie.getName())){
                    lang = cookie.getValue();
                }
            }
        }else{
            Cookie cookie = new Cookie("lang",lang);
            cookie.setMaxAge(365 * 24 * 3600);
            cookie.setPath("/");
            ((HttpServletResponse)servletResponse).addCookie(cookie);
        }
        ((HttpServletRequest)servletRequest).getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new java.util.Locale(lang));
        ((HttpServletRequest)servletRequest).getSession().setAttribute("currentLocale",lang);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
